package ao

import (
	"context"
	"time"

	compb "gitee.com/micro-services/protocol/common"
	pb "gitee.com/micro-services/protocol/user/server"
	"micro.user.action.server/common"
	"micro.user.action.server/do"
	"micro.user.action.server/impl"
	"micro.user.action.server/integration"
	"micro.user.action.server/models"
)

func WxUserLogin(ctx context.Context, r *pb.WxUserLoginReq, w *pb.WxUserLoginRsp) error {
	factory := impl.WxUserBuilder()
	wxUserInfoRsp, err := integration.GetWxUserInfo(ctx, &pb.GetWxUserInfoReq{
		Code: r.Code,
	})
	if err != nil {
		return err
	}
	if wxUserInfoRsp == nil {
		return common.WxUserIsNotExist
	}

	userId, err := factory.UserRegistry(&models.VsWxUser{
		OpenId:      wxUserInfoRsp.OpenId,
		UnionId:     wxUserInfoRsp.UnionId,
		CreatedTime: time.Now().Unix(),
		UpdatedTime: time.Now().Unix(),
	})
	if err != nil {
		return err
	}

	jwtRsp, err := integration.GenerateToken(ctx, &pb.GenerateTokenReq{
		UserID:   userId,
		Platform: compb.UserPlatFormType_MINI_PROGRAM_USER,
	})
	if err != nil {
		return err
	}

	w.RetCode = common.Code
	w.Msg = common.Success
	w.Expiration = jwtRsp.Expiration
	w.Token = jwtRsp.Token

	return nil
}

func WxUserInfo(ctx context.Context, r *pb.WxUserInfoReq, w *pb.WxUserInfoRsp) error {
	factory := impl.WxUserBuilder()
	info, err := factory.QueryUserInfo(r.WxUserID)
	if err != nil {
		return err
	}

	w.RetCode = common.Code
	w.Msg = common.Success
	w.WxUserInfo = do.ConvertWxUserInfo(info)

	return nil
}

func UpdateWxUserInfo(ctx context.Context, r *pb.UpdateWxUserInfoReq, w *pb.UpdateWxUserInfoRsp) error {
	factory := impl.WxUserBuilder()
	err := factory.UpdateWxUserInfo(&models.VsWxUser{
		WxUserId:     r.WxUserInfo.WxUserID,
		WxUserName:   r.WxUserInfo.WxUserName,
		WxAvatarIcon: r.WxUserInfo.WxAvatarIcon,
		Gender:       r.WxUserInfo.Gender,
		Phone:        r.WxUserInfo.Phone,
		UpdatedTime:  time.Now().Unix(),
	})
	if err != nil {
		return err
	}

	w.RetCode = common.Code
	w.Msg = common.Success

	return nil
}
